package com.imxiaoyu.wifi.adb.view;

import com.imxiaoyu.wifi.adb.utils.ConnectUtils;
import com.imxiaoyu.wifi.adb.utils.SettingsEntity;
import com.imxiaoyu.wifi.adb.utils.SettingsUtils;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class IndexView {


    private JPanel jPanel;

    private JTextField tf_adb_path;
    private JButton btn_adb_path;
    private JButton btn_refresh;
    private JTable tb_now;
    private JTable tb_history;
    private JButton btn_test_connect;
    private JTextField tf_ip_port;

    private List<Map<String, Object>> nowDeviceList = new ArrayList<>();
    private List<Map<String, Object>> historyDeviceList = new ArrayList<>();

    public void startView() {
        JFrame frame = new JFrame("Wifi Adb");
        frame.setContentPane(jPanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        frame.setSize(new Dimension(880, 500));

        btn_adb_path.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //设置一下adb.exe的路径
                JFileChooser fileChooser = new JFileChooser("D:\\");
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int returnVal = fileChooser.showOpenDialog(fileChooser);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    String filePath = fileChooser.getSelectedFile().getAbsolutePath();//这个就是你选择的文件夹的路径
                    tf_adb_path.setText(filePath);
                    System.out.print("\n选中的路径：" + filePath);
                    SettingsEntity entity = SettingsUtils.getSettings();
                    entity.setWifiAdbPath(filePath);
                    SettingsUtils.setSettings(entity);
                }
            }
        });

        btn_test_connect.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //通过手动输入ip和端口的形式，直接连接设备
                String deviceName=tf_ip_port.getText();
                ConnectUtils.connect(deviceName);
                initList();
            }
        });

        btn_refresh.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //刷新列表
                initList();
            }
        });

        //初始化adv.exe的路径信息
        SettingsEntity entity = SettingsUtils.getSettings();
        tf_adb_path.setText(entity.getWifiAdbPath());

        initList();
    }


    private void initList() {

        nowDeviceList = SettingsUtils.getAllDevice();
        NowListModel listModel = new NowListModel();

        tb_now.setModel(listModel);//设置需要显示的数据
        tb_now.setRowHeight(36);

        //这个setCellEditor和setCellRenderer必须分别new，不然的话点击按钮的时候会有点小问题
        tb_now.getColumnModel().getColumn(3).setCellEditor(new NowListEditor());//加入点击监听
        tb_now.getColumnModel().getColumn(3).setCellRenderer(new NowListEditor());//加入操作按钮

        tb_now.setRowSelectionAllowed(false);


        historyDeviceList = SettingsUtils.getSettings().getPhoneList();

        HistoryListModel historyListModel = new HistoryListModel();

        tb_history.setModel(historyListModel);
        tb_history.setRowHeight(36);

        tb_history.getColumnModel().getColumn(3).setCellEditor(new HistoryListEditor());
        tb_history.getColumnModel().getColumn(3).setCellRenderer(new HistoryListEditor());

        tb_history.setRowSelectionAllowed(false);

    }


    public class NowListModel extends AbstractTableModel {


        /**
         * 得到表格行数
         */
        @Override
        public int getRowCount() {
            if (nowDeviceList.size() == 0) {
                //列表空的话，标题也不显示
                return 0;
            }
            return nowDeviceList.size() + 1;
        }

        /**
         * 重写方法，得到表格列数
         */
        @Override
        public int getColumnCount() {
            return 4;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            if (rowIndex == 0) {
                if (columnIndex == 0) {
                    return "型号";
                }
                if (columnIndex == 1) {
                    return "设备名称";
                }
                if (columnIndex == 2) {
                    return "transport_id";
                }
                if (columnIndex == 3) {
                    return "操作";
                }
            }

            if (columnIndex == 0) {
                return nowDeviceList.get(rowIndex - 1).get("model");
            }
            if (columnIndex == 1) {
                return nowDeviceList.get(rowIndex - 1).get("name");
            }
            if (columnIndex == 2) {
                return nowDeviceList.get(rowIndex - 1).get("transport_id");
            }
            return "";
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            // 带有按钮列的功能这里必须要返回true不然按钮点击时不会触发编辑效果，也就不会触发事件。
            if (column == 3) {
                return true;
            } else {
                return false;
            }
        }

    }

    public class HistoryListModel extends AbstractTableModel {


        /**
         * 得到表格行数
         */
        @Override
        public int getRowCount() {
            if (historyDeviceList.size() == 0) {
                return 0;
            }
            return historyDeviceList.size() + 1;
        }

        /**
         * 重写方法，得到表格列数
         */
        @Override
        public int getColumnCount() {
            return 4;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            if (rowIndex == 0) {
                if (columnIndex == 0) {
                    return "型号";
                }
                if (columnIndex == 1) {
                    return "设备名称";
                }
                if (columnIndex == 3) {
                    return "操作";
                }
                if (columnIndex == 2) {
                    return "transport_id";
                }
            }

            if (columnIndex == 1) {
                return historyDeviceList.get(rowIndex - 1).get("name");
            }
            if (columnIndex == 0) {
                return historyDeviceList.get(rowIndex - 1).get("model");
            }
            if (columnIndex == 2) {
                return historyDeviceList.get(rowIndex - 1).get("transport_id");
            }
            return "";
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            // 带有按钮列的功能这里必须要返回true不然按钮点击时不会触发编辑效果，也就不会触发事件。
            if (column == 3) {
                return true;
            } else {
                return false;
            }
        }

    }

    public class NowListEditor extends AbstractCellEditor implements TableCellRenderer,
            TableCellEditor {

        private JPanel panel;
        private JButton btnSave = null;
        private JButton btnDis = null;
        private JButton btnConnect = null;
        private int clickRow;

        public NowListEditor() {
            initButton();

            initPanel();

            panel.add(btnConnect);
            panel.add(btnDis);
            panel.add(btnSave);
        }

        private void initButton() {
            /**
             * 初始化按钮
             */
            btnConnect = new JButton("链接");
            btnDis = new JButton("断开");
            btnSave = new JButton("保存");

            /**
             * 设置按钮监听
             */
            btnConnect.addActionListener(new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.print("\n链接");
                    System.out.print("；clickRow：" + clickRow);

                    String deviceName = nowDeviceList.get(clickRow - 1).get("name") + "";
                    String ip = ConnectUtils.getDeviceIp(deviceName);
                    String port = "5555";
                    ConnectUtils.setDevicePort(deviceName, port);
                    ConnectUtils.connect(ip + ":" + port);
                    initList();
                }
            });
            btnDis.addActionListener(new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.print("\n断开");
                    System.out.print("；clickRow：" + clickRow);
                    ConnectUtils.disconnect(nowDeviceList.get(clickRow - 1).get("name") + "");
                    initList();
                }
            });
            btnSave.addActionListener(new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.print("\n保存");
                    System.out.print("；clickRow：" + clickRow);
                    SettingsUtils.saveDevice(nowDeviceList.get(clickRow - 1));
                    initList();
                }
            });
        }

        /**
         * 初始化画板
         */
        private void initPanel() {
            panel = new JPanel();
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            /**
             * 这里是处理显示
             */
            panel.setBackground(new Color(255, 255, 255));
            if (row != 0) {
                panel.removeAll();

                String deviceName = nowDeviceList.get(row - 1).get("name") + "";

                if (ConnectUtils.isUsb(deviceName)) {
                    //这是一个有线设备
                    if (!ConnectUtils.isUsbConnectWifi(nowDeviceList, deviceName)) {
                        //这个有限设备还没链接wifi
                        panel.add(btnConnect);
                    }
                } else {
                    //这是一个wifi设备
                    panel.add(btnDis);

                    if (!SettingsUtils.isHaveDevice(nowDeviceList.get(row - 1))) {
                        //这个wifi设备还没有保存
                        panel.add(btnSave);
                    }
                }
                return panel;
            }
            return null;
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value,
                                                     boolean isSelected, int row, int column) {
            /**
             * 这里是处理点击
             */
            clickRow = row;
            panel.setBackground(new Color(255, 255, 255));
            if (row != 0) {
                panel.removeAll();

                String deviceName = nowDeviceList.get(row - 1).get("name") + "";
                if (ConnectUtils.isUsb(deviceName)) {
                    System.out.print("\n有线设备："+deviceName);
                    //这是一个有线设备
                    if (!ConnectUtils.isUsbConnectWifi(nowDeviceList, deviceName)) {
                        //这个有限设备还没链接wifi
                        panel.add(btnConnect);//显示连接按钮
                    }
                    //如果有线设备已经链接了，就不再显示连接按钮
                } else {
                    //这是一个wifi设备
                    panel.add(btnDis);//如果列表里面有wifi设备，证明肯定是链接状态了的，所以只需要显示断开按钮

                    if (!SettingsUtils.isHaveDevice(nowDeviceList.get(row - 1))) {
                        //这个wifi设备还没有保存
                        panel.add(btnSave);//没保存就显示保存按钮，已保存则不显示
                    }
                }

                return panel;
            }
            return null;
        }

        @Override
        public Object getCellEditorValue() {
            return null;
        }
    }

    public class HistoryListEditor extends AbstractCellEditor implements TableCellRenderer,
            TableCellEditor {

        private JPanel panel;
        private JButton btnSave = null;
        private JButton btnDis = null;
        private JButton btnConnect = null;
        private int clickRow;

        public HistoryListEditor() {
            initButton();

            initPanel();

            panel.add(btnConnect);
            panel.add(btnDis);
            panel.add(btnSave);
        }

        private void initButton() {
            /**
             * 初始化按钮
             */
            btnConnect = new JButton("链接");
            btnDis = new JButton("断开");
            btnSave = new JButton("删除");

            /**
             * 监听点击
             */
            btnConnect.addActionListener(new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.print("\n链接");
                    ConnectUtils.connect(historyDeviceList.get(clickRow - 1).get("name") + "");
                    System.out.print("；clickRow：" + clickRow);
                    initList();
                }
            });
            btnDis.addActionListener(new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.print("\n断开");
                    ConnectUtils.disconnect(historyDeviceList.get(clickRow - 1).get("name") + "");
                    System.out.print("；clickRow：" + clickRow);
                    initList();
                }
            });
            btnSave.addActionListener(new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.print("\n删除");
                    System.out.print("；clickRow：" + clickRow);
                    SettingsUtils.removeDevice(historyDeviceList.get(clickRow - 1).get("id") + "");
                    initList();
                }
            });

        }

        /**
         * 初始化画板
         */
        private void initPanel() {
            panel = new JPanel();
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            panel.setBackground(new Color(255, 255, 255));
            if (row != 0) {
                panel.removeAll();

                String deviceName=historyDeviceList.get(row-1).get("name")+"";
                if(ConnectUtils.isWifiConnect(nowDeviceList,deviceName)){
                    System.out.print("wifi已连接");
                    //这个wifi设备已经链接
                    panel.add(btnDis);//已连接，显示断开按钮
                }else{
                    //还没链接
                    panel.add(btnConnect);//未连接，显示连接按钮
                }
                panel.add(btnSave);//显示删除按钮
                return panel;
            }
            return null;
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value,
                                                     boolean isSelected, int row, int column) {
            clickRow = row;
            panel.setBackground(new Color(255, 255, 255));
            if (row != 0) {
                panel.removeAll();

                String deviceName=historyDeviceList.get(row-1).get("name")+"";
                if(ConnectUtils.isWifiConnect(nowDeviceList,deviceName)){
                    //这个wifi设备已经链接
                    panel.add(btnDis);//已连接，显示断开按钮
                }else{
                    //还没链接
                    panel.add(btnConnect);//未连接，显示连接按钮
                }
                panel.add(btnSave);//显示删除按钮
                return panel;
            }
            return null;
        }

        @Override
        public Object getCellEditorValue() {
            return null;
        }
    }

}
